package runCORBA;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.PortableServer.POAManagerPackage.AdapterInactive;
import org.omg.PortableServer.POAPackage.ObjectNotActive;
import org.omg.PortableServer.POAPackage.ServantAlreadyActive;
import org.omg.PortableServer.POAPackage.WrongPolicy;

import client.CommandClient;
import udp.UdpServer;
import udp.UdpClient;
import fe.FrontEndImpl;

public class runCORBA{


	public static void main(String[] args)throws InvalidName,WrongPolicy,ServantAlreadyActive,ObjectNotActive, FileNotFoundException, AdapterInactive {
		CommandClient.printHeader("Front-end");

		runOrb(args);
	}
	

	public static void runOrb(String [] args)throws InvalidName,WrongPolicy,ServantAlreadyActive,ObjectNotActive, FileNotFoundException, AdapterInactive {

		//initialize orb
		ORB orb = ORB.init(args, null);
		POA frontEndPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
		
		// activate object
		FrontEndImpl FrontEndObject = new FrontEndImpl("frontend",2000);
		
		byte[] FrontEndID = frontEndPOA.activate_object(FrontEndObject);
		
		//get reference
		org.omg.CORBA.Object ref_FrontEnd = frontEndPOA.id_to_reference(FrontEndID);
		
		// IOR
		String frontEndIOR = orb.object_to_string(ref_FrontEnd);
		
		
		// keep the ior in a text file
		write(frontEndIOR);
		
		// activate and run ORB
		frontEndPOA.the_POAManager().activate();

	}
	
	public static void write(String ior){
		BufferedWriter writer = null;

		String dir = System.getProperty("user.home");
		dir = dir.concat(System.getProperty("file.separator")).concat("ior");

		try {
			writer = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(dir)));
			writer.write(ior);
		} catch (IOException ex) {
			// report
		} finally {
			try {writer.close();} catch (Exception ex) {}
		}
	}
}
